package cn.servlet;
import cn.entity.Student;
import cn.service.StudentService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

@WebServlet("/students")
public class Servlet extends HttpServlet {
    private StudentService studentService = new StudentService();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        try {
            List<Student> students = studentService.getAll();
            request.setAttribute("students", students);
            request.getRequestDispatcher("/index.jsp").forward(request, response);
        } catch (SQLException e) {
            throw new ServletException(e);
        }
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        String action = request.getParameter("action");
        try {
            if ("add".equals(action)) {
                String name = request.getParameter("name");
                int age = Integer.parseInt(request.getParameter("age"));
                char gender = request.getParameter("gender").charAt(0);
                String major = request.getParameter("major");

                Student student = new Student(name, age, gender, major);
                studentService.addStudent(student);
            } else if ("update".equals(action)) {
                int id = Integer.parseInt(request.getParameter("id"));
                String name = request.getParameter("name");
                int age = Integer.parseInt(request.getParameter("age"));
                char gender = request.getParameter("gender").charAt(0);
                String major = request.getParameter("major");

                Student student = new Student();
                student.setId(id);
                student.setName(name);
                student.setAge(age);
                student.setGender(gender);
                student.setMajor(major);
                studentService.UpdateStudent(student);
            } else if ("delete".equals(action)) {
                int id = Integer.parseInt(request.getParameter("id"));
                studentService.deleteStudent(id);
            }
            response.sendRedirect(request.getContextPath() + "/students");
        } catch (NumberFormatException | SQLException e) {
            // 添加错误处理
            request.setAttribute("error", "操作失败，请检查输入数据！");
            request.getRequestDispatcher("/index.jsp").forward(request, response);
        }
    }
}
